package com.java.tutorials.spring.AfterReturningAdvice;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;

/**
 * Created by xuzhike on 2016/1/28.
 * http://www.java2s.com/Code/Java/Spring/CheckLogicInAfterReturningAdvice.htm
 * Check Logic In AfterReturningAdvice
 */
public class CheckLogicInAfterReturningAdvice {
    public static void main(String[] args) {
        KeyGenerator target = new KeyGenerator();

        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(target);
        factory.addAdvice(new WeakKeyCheckAdvice());

        KeyGenerator keyGen = (KeyGenerator) factory.getProxy();

        System.out.println("Key: " + keyGen.getKey());
    }
}

class KeyGenerator {
    public static final long WEAK_KEY = 1L;

    public static final long STRONG_KEY = 2L;

    public long getKey() {
        return WEAK_KEY;
        // return STRONG_KEY;
    }
}

class WeakKeyCheckAdvice implements AfterReturningAdvice {

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
            throws Throwable {

        if ((target instanceof KeyGenerator) && ("getKey".equals(method.getName()))) {
            long key = (Long) returnValue;

            if (key == KeyGenerator.WEAK_KEY) {
                System.out.println("a weak key");
            }
        }
    }
}
